package com.tidc.seaservermodel.aspect;

import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/9/27 20:48
 * @description：
 * @modified By：
 * @version:
 */
@Aspect
@Component
public class AffectedCount {
    private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
//    切入点
    @Pointcut("@annotation(com.tidc.seaservermodel.aspect.Affected)")
    public void affected() {}
    /**
     * 在切点之前织入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("affected()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 打印请求相关参数
        logger.info("========================================== SQLStart ==========================================");
        // 打印调用 controller 的全路径以及执行方法
        logger.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求入参
        logger.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));
    }

    /**
     * 在切点之后织入
     * @throws Throwable
     */
    @After("affected()")
    public void doAfter() throws Throwable {
        // 接口结束后换行，方便分割查看
        logger.info("=========================================== SQLEnd ===========================================" );
    }
    /**
     * 环绕
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("affected()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        int result = (int) proceedingJoinPoint.proceed();
        // 打印出参
        if(result<1){
            logger.error("sql {}.{} 执行失败",proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName());
            logger.info("形参   : {}", new Gson().toJson(proceedingJoinPoint.getArgs()));
            throw new SQLException("sql执行失败 ");

        }
        return result;
    }
}
